﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Text;

namespace PlutoStudio.Data.Common
{
    [AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)]
    public sealed class ColumnAttribute : Attribute
    {
        public string ColumnName { get; private set; }

        public int Size { get; private set; }

        public DbType DbType { get; set; }

        public bool Nullable { get; set; }

        public bool IsPrimaryKey { get; set; }

        public bool IsAutoIncrement { get; set; }

        public ColumnAttribute()
        {

        }

        public ColumnAttribute(string name)
        {
            this.ColumnName = name;
        }
    }

    [AttributeUsage(AttributeTargets.Class, Inherited = false, AllowMultiple = false)]
    public sealed class TableAttribute : Attribute
    {
        public string TableName { get; private set; }

        public bool SplitTable { get; private set; }

        public int DatabaseId { get; private set; }

        public Func<object, int> DataBaseSelector { get; set; }

        public Func<object, string> TableNameSelector { get; set; }

        public int GetDatabaseId(object entity)
        {
            if (SplitTable)
            {
                return DataBaseSelector(entity);
            }
            return DatabaseId;
        }

        public int GetDatabaseId()
        {
            return DatabaseId;
        }

        public TableAttribute(string name,bool splitTable=false,int databaseId=0)
        {
            this.TableName = name;
            this.SplitTable = splitTable;
            this.DatabaseId = databaseId;
        }

        public TableAttribute(string name, Type databaseSelectorType, string databaseSelectorMethodName,Type tableNameSelectorType,string tableNameSelectorMethodName)
        {
            SplitTable = true;
            this.TableName = name;
            var databaseSelectorMethod = databaseSelectorType.GetMethod(databaseSelectorMethodName);
            var tableNameSelectorMethod = tableNameSelectorType.GetMethod(tableNameSelectorMethodName);

            this.DataBaseSelector = Delegate.CreateDelegate(typeof(Func<object, int>), databaseSelectorMethod) as Func<object, int>;
            this.TableNameSelector = Delegate.CreateDelegate(typeof(Func<object,string>),tableNameSelectorMethod) as Func<object,string>;
        }
    }
}
